<script lang="ts" setup>
import { ref, Ref, reactive } from "vue"
import { useRouter } from "vue-router"
import { useUserStore } from "@/store/modules/user"
import { UserFilled } from "@element-plus/icons-vue"
import Modal from "@/components/modal/index.vue"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import Logo from "../Logo/index.vue"
import { checkEmail, checkPhone, strictCheckPassword } from "@/utils/index"
import { editUserApi } from "@/api/user/index"
import { type IEditUserParams } from "@/api/user/types/index"
import { storeToRefs } from "pinia"
import { useMqttStore } from "@/store/modules/mqtt"
interface IPasswrod {
  password: string
  newPassword: string
  confirmPassword: string
}

interface IInfo {
  phone: string
  email: string
  remarks: string
}

const router = useRouter()
const mqttStore = useMqttStore()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const { offDevicesCounts } = storeToRefs(mqttStore)
const logoOutModalRef: Ref<typeof Modal | null> = ref(null)
const userInfoModalRef: Ref<typeof Modal | null> = ref(null)
const passwordForm = reactive<IPasswrod>({
  password: "",
  newPassword: "",
  confirmPassword: ""
})

const infoForm = reactive<IInfo>({
  phone: userInfo.value.user_telphone ?? "",
  email: userInfo.value.user_email ?? "",
  remarks: userInfo.value.remarks ?? ""
})

const passwordFormRef = ref<FormInstance>()
const infoFormRef = ref<FormInstance>()

const validStatus = ref(true)

const checkSame = (rule: any, value: string, callback: any) => {
  if (!value) {
    rule.message = "请再次输入新密码"
    callback(new Error("请再次输入新密码"))
    return
  }

  if (value !== passwordForm.newPassword) {
    rule.message = "新密码不一致"
    callback(new Error("密码不一致"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<IPasswrod>>({
  password: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: strictCheckPassword }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { required: true, validator: strictCheckPassword, trigger: "blur" }
  ],
  confirmPassword: [{ required: true, trigger: "blur", validator: checkSame }]
})

const infoRules = reactive<FormRules<IInfo>>({
  phone: [
    {
      message: "手机号格式不正确",
      validator: checkPhone
    }
  ],
  email: [
    {
      message: "邮箱格式不正确",
      validator: checkEmail
    }
  ]
})

const eidtPassword = ref<boolean>(false) // 编辑密码
const eidtInfo = ref<boolean>(false) // 编辑用信息
const infoTitle = ref<string>("用户信息") // 用户信息title
// 退出弹窗
const logout = () => {
  ;(logoOutModalRef as Ref<typeof Modal>).value.showModal()
}

// 退出确认
const handleLogoOutConfirm = async () => {
  await userStore.logout()
  ElMessage.success("退出成功")
  router.push("/login")
}

// 取消退出
const handleCloseLogoOut = () => {
  ;(logoOutModalRef as Ref<typeof Modal>).value.closeModal()
}

// 用户信息退出
const handleCloseUserInfo = () => {
  eidtPassword.value = false
  eidtInfo.value = false
  infoTitle.value = "用户信息"
  resetData()
}

// 用户信息
const handleClickInfo = () => {
  ;(userInfoModalRef as Ref<typeof Modal>).value.showModal()
}

// 用户信息确认
const handleUserInfoConfirm = async () => {
  // 处于编辑状态
  if (eidtPassword.value || eidtInfo.value) {
    const params: Partial<IEditUserParams> = {
      id: userInfo.value.id
    }

    if (eidtPassword.value) {
      await passwordFormRef.value?.validate((valid) => {
        console.info(valid)
        validStatus.value = valid
        if (valid) {
          params.user_password = passwordForm.newPassword
          params.oldpassword = passwordForm.password
        }
      })
    }

    // 编辑信息
    if (eidtInfo.value) {
      await infoFormRef.value?.validate((valid) => {
        validStatus.value = valid
        if (valid) {
          params.user_email = infoForm.email
          params.remarks = infoForm.remarks
          params.user_telphone = infoForm.phone
        }
      })
    }

    if (validStatus.value) {
      const res = await editUserApi(params)
      const { result, return_message } = res

      if (result === 200) {
        ElMessage.success("修改成功")
        userStore.getInfo(false)
        ;(userInfoModalRef as Ref<typeof Modal>).value.closeModal()
      } else {
        ElMessage.error(return_message)
      }
    }
  } else {
    // 正常显示状态 未编辑
    eidtInfo.value = true
    infoTitle.value = "编辑用户信息"
  }
}

const handleEditPasswrod = () => {
  eidtPassword.value = true
  infoTitle.value = "编辑用户信息"
}

// 重置数据
const resetData = () => {
  infoFormRef.value?.resetFields()
  passwordFormRef.value?.resetFields()
}

// 关闭弹窗
const handleCloseModal = () => {
  handleCloseUserInfo()
}

const handleClickStatus = () => {
  if (offDevicesCounts.value !== 0) router.push("/architecture-management/index")
}
</script>

<template>
  <div class="navigation-bar bg-#387af6">
    <Logo />
    <div class="right-menu">
      <el-popover
        :popper-style="{ textAlign: 'center' }"
        placement="top"
        trigger="hover"
        :content="offDevicesCounts !== 0 ? '设备离线' : '设备正常'"
      >
        <template #reference>
          <div @click="handleClickStatus" flex items-center cursor-pointer>
            <span v-if="offDevicesCounts !== 0" text-white mr-5px>{{ `设备离线(${offDevicesCounts})` }} </span>
            <SvgIcon :name="offDevicesCounts !== 0 ? 'abnormal' : 'normal'" class="w-24px! h-24px!" />
          </div>
        </template>
      </el-popover>

      <el-dropdown class="right-menu-item">
        <div class="right-menu-avatar">
          <span text-white>{{ userStore.username }}</span>
          <el-avatar :icon="UserFilled" :size="30" />
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <span @click="handleClickInfo">
              <el-dropdown-item>用户信息</el-dropdown-item>
            </span>
            <el-dropdown-item divided @click="logout">
              <span style="display: block">退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <Modal ref="logoOutModalRef" title="安全退出" width="520" @close="handleCloseModal">
      <template #content>
        <span text-16px class="text-#252526">确定退出账号吗？</span>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button class="w-105px!" @click="handleCloseLogoOut">取消</el-button>
          <el-button class="w-105px! bg-#387af6!" type="primary" @click="handleLogoOutConfirm"> 确定 </el-button>
        </div>
      </template>
    </Modal>

    <Modal ref="userInfoModalRef" :title="infoTitle" width="620" @close="handleCloseModal">
      <template #content>
        <div>
          <el-row mb-35px>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>姓名：</span>
                <span>{{ userInfo.user_name }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>账号：</span>
                <span>{{ userInfo.user_number }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <div flex v-if="!eidtPassword">
                <span w-85px text-end pr-14px mr-14px>密码：</span>
                <span>********</span>
                <span ml-20px class="text-#387AF6" @click="handleEditPasswrod" cursor-pointer>修改密码</span>
              </div>

              <el-form
                v-else
                ref="passwordFormRef"
                style="max-width: 600px"
                :model="passwordForm"
                :rules="rules"
                label-width="auto"
              >
                <el-row mb-15px>
                  <el-col :span="12">
                    <el-form-item label="密码：" prop="password" label-width="100">
                      <el-input
                        v-model="passwordForm.password"
                        placeholder="请输入旧密码"
                        type="password"
                        show-password
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="新密码：" prop="newPassword" label-width="100">
                      <el-input
                        v-model="passwordForm.newPassword"
                        placeholder="请输入新密码"
                        type="password"
                        show-password
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="确认密码：" prop="confirmPassword" label-width="100">
                      <el-input
                        v-model="passwordForm.confirmPassword"
                        placeholder="请再次输入新密码"
                        type="password"
                        show-password
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
          </el-row>

          <div my-20px border-b-1px border-b-solid class="border-b-#e9ebed" />

          <el-row>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>所属分区：</span>
                <span>--</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>角色：</span>
                <span>{{ userInfo.user_role_name }}</span>
              </div>
            </el-col>
          </el-row>

          <div my-20px border-b-1px border-b-solid class="border-b-#e9ebed" />

          <el-form
            v-if="eidtInfo"
            ref="infoFormRef"
            :rules="infoRules"
            style="max-width: 600px"
            :model="infoForm"
            label-width="auto"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号码：" prop="phone" label-width="100">
                  <el-input v-model="infoForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="邮箱：" prop="email" label-width="100">
                  <el-input v-model="infoForm.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remarks" label-width="100">
                  <el-input clearable type="textarea" v-model="infoForm.remarks" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-row v-if="!eidtInfo" mb-35px>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>手机号码：</span>
                <span>{{ userInfo.user_telphone }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>邮箱：</span>
                <span>{{ userInfo.user_email }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row v-if="!eidtInfo">
            <el-col :span="12">
              <div flex>
                <span w-85px text-end pr-14px mr-14px>备注：</span>
                <span>{{ userInfo.remarks }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #footer>
        <div pr-20px>
          <el-button v-if="eidtPassword || eidtInfo" class="w-105px!" @click="handleCloseUserInfo">取消</el-button>
          <el-button class="w-105px! bg-#387af6!" type="primary" @click="handleUserInfoConfirm">
            {{ eidtPassword || eidtInfo ? "确认" : "编辑" }}
          </el-button>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.navigation-bar {
  height: var(--v3-navigationbar-height);
  overflow: hidden;
  color: var(--v3-navigationbar-text-color);
  display: flex;
  justify-content: space-between;

  .breadcrumb {
    flex: 1;
    // 参考 Bootstrap 的响应式设计将宽度设置为 576
    @media screen and (max-width: 576px) {
      display: none;
    }
  }
  .sidebar {
    flex: 1;
    // 设置 min-width 是为了让 Sidebar 里的 el-menu 宽度自适应
    min-width: 0px;
    :deep(.el-menu) {
      background-color: transparent;
    }
    :deep(.el-sub-menu) {
      &.is-active {
        .el-sub-menu__title {
          color: var(--el-color-primary) !important;
        }
      }
    }
  }
  .right-menu {
    margin-right: 10px;
    height: 100%;
    display: flex;
    align-items: center;
    .right-menu-item {
      padding: 0 10px;
      cursor: pointer;
      .right-menu-avatar {
        display: flex;
        align-items: center;
        .el-avatar {
          margin-left: 10px;
        }
        span {
          font-size: 16px;
        }
      }
    }
  }
}

:deep(.el-dialog) {
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  border-radius: 5px;
  background: #f7f9fb;

  .el-dialog__body {
    padding: 20px;
  }
}
:deep(.device_popper) {
  &.is-light {
    text-align: center !important;
  }
}
</style>
